text:
Q: Number of ways people $3$ men and $7$ women can fit in three cars given the stated restrictions 3 men, 7 women and a married couple travel together with three cars. Each car can only fit four people. Given that all of them can drive cars, find the number of ways they can get in the car such that:
(i) everyone in each car must be same gender,
(ii) a married couple must sit together in a car

A: (i) group of men already decided , left 8 women need to be divided in 2 groups each of 4 which has $\frac{8!}{4!4!2!}$ ways =35.Now we are left with 3 groups which are to be arranged in 3 cars(assuming cars are different) hence multiply 70 by 3!=210
(ii) We will choose 2 people who sit with married couple, and then reapeat the whole process entirely as done is first case=210×45


text:
Q: What is the difference between -O0 ,-O1 and -g I am wondering about the use of -O0,-O1 and -g for enabling debug symbols in a lib.
Some suggest to use -O0 to enable debug symbols and some suggest to use -g.
So what is the actual difference between -g and -O0 and what is the difference between -01 and -O0 and which is best to use.

A: -OX specify the optimisation level that the compiler will perform. -g is used to generate debug symbols.

A: From GCC manual
http://gcc.gnu.org/onlinedocs/

3.10 Options That Control Optimization`
-O
-O1
Optimize. Optimizing compilation takes somewhat more time, and a lot more memory for a large function. With -O, the compiler tries to reduce code size and execution time, without performing any optimizations that take a great deal of compilation time.`
-O2
Optimize even more. GCC performs nearly all supported optimizations that do not involve a space-speed tradeoff. As compared to -O, this option increases both compilation time and the performance of the generated code.`
-O3
Optimize yet more. -O3 turns on all optimizations specified by -O2 and also turns on the -finline-functions, -funswitch-loops, -fpredictive-commoning, -fgcse-after-reload, -ftree-vectorize and -fipa-cp-clone options.`
-O0
Reduce compilation time and make debugging produce the expected results. This is the default. `
-g
Produce debugging information in the operating system's native format (stabs, COFF, XCOFF, or DWARF 2). GDB can work with this debugging information.`

A: -O0 doesn't enable debug symbols, it just disables optimizations in the generated code so debugging is easier (the assembly code follows the C code more or less directly). -g tells the compiler to produce symbols for debugging.
It's possible to generate symbols for optimized code (just continue to specify -g), but trying to step through code or set breakpoints may not work as you expect because the emitted code will likely not "follow along" with the original C source closely.  So debugging in that situation can be considerably trickier.
-O1 (which is the same as -O) performs a minimal set of optimizations. -O0 essentially tells the compiler not to optimize.  There are a slew of options that allow a very fine control over how you might want the compiler to perform:  http://gcc.gnu.org/onlinedocs/gcc-4.6.3/gcc/Optimize-Options.html#Optimize-Options

A: -O0 is optimization level 0 (no optimization, same as omitting the -O argument)
-O1 is optimization level 1.
-g generates and embeds debugging symbols in the binaries.
See the gcc docs and manpages for further explanation.
For doing actual debugging, debuggers are usually not able to make sense of stuff that's been compiled with optimization, though debug symbols are useful for other things even with optimization, such as generating a stacktrace.

A: As mentioned by others, -O set of options indicate the levels of optimization that must be done by the compiler whereas, the -g option adds the debugging symbols.
For a more detailed understanding, please refert to the following links
http://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html#Optimize-Options
http://gcc.gnu.org/onlinedocs/gcc/Debugging-Options.html#Debugging-Options

redpajama_set_name: RedPajamaStackExchange


text:
Q: Adding own data - QGIS I'm using QGIS and I want to map some specific shops in a city. I have collected X and Y coordinates and names so now I would like to add as a layer and then connect with a map.
Does anyone know how to add own collected data?


text:
Q: Junit test Rxjava method I tested the Rxjava methods many times without problem but now i faced with this problem :
Null pointer exception in this subscribeOn(Schedulers.io()) line.
 fun registerPhone(phoneNumber: String, nationalId: String) {
        val disposable =
            mRepository.getRegister(jsonObjectToRequestBody(phoneNumber, nationalId))
                .subscribeOn(Schedulers.io()) //NPE in this line
.
.
.
}

I used Mockito when before it but i dont know why this problem cause until now and this is my test method :
class ViewModelTest : BaseTest() {
    private val mResponseBody = ResponseBody.create(
        null, ""
    )
    private var mGson= Gson()
    private val mRequestBody = RequestBody.create(null, mGson.toJson(Register("123", "123")))
    .
    .
    .

    @Test
    fun registerPhone_success() {
        Mockito.`when`(mRepository.getRegister(mRequestBody)).thenReturn(
            Single.just(
                Response.success(mResponseBody)
            )
        )
        mViewModel.registerPhone("123", "123")
}
}

This is my base test :
open class BaseTest {
    @Before
    fun setUpClass() {
        RxJavaPlugins.reset()
        RxAndroidPlugins.reset()
        val immediate = object : Scheduler() {
            override fun scheduleDirect(run: Runnable, delay: Long, unit: TimeUnit): Disposable {

                return super.scheduleDirect(run, 0, unit)
            }

            override fun createWorker(): Worker {
                return ExecutorScheduler.ExecutorWorker(Executor { it.run() }, true)
            }
        }
        RxJavaPlugins.setInitIoSchedulerHandler { scheduler -> immediate }
        RxJavaPlugins.setInitComputationSchedulerHandler { scheduler -> immediate }
        RxJavaPlugins.setInitNewThreadSchedulerHandler { scheduler -> immediate }
        RxJavaPlugins.setInitSingleSchedulerHandler { scheduler -> immediate }
        RxAndroidPlugins.setInitMainThreadSchedulerHandler { scheduler -> immediate }

        RxJavaPlugins.setIoSchedulerHandler { Schedulers.trampoline() }
        RxJavaPlugins.setComputationSchedulerHandler { Schedulers.trampoline() }
        RxJavaPlugins.setNewThreadSchedulerHandler { Schedulers.trampoline() }
        RxAndroidPlugins.setInitMainThreadSchedulerHandler { Schedulers.trampoline() }
    }

    @After
    fun tearDownClass() {
        RxJavaPlugins.reset()
        RxAndroidPlugins.reset()
    }
}

A: I think you are testing this in wrong way. Try this:
class ViewModelTest : BaseTest() {
    private val mResponseBody = ResponseBody.create(
        null, ""
    )
    private var mGson= Gson()

    private val mRepository = mock()

    @Test
    fun registerPhone_success() {
        whenever(mRepository.getRegister(any())).thenReturn(
            Single.just(
                Response.success(mResponseBody)
            )
        )
        mViewModel.registerPhone("123", "123")
}
}


text:
Q: using GetFrontBufferData(), & place screenshot in separate device backbuffer Ok, so for anyone who's used it much - this should be a SUPER easy question.
I was just searching online for a way to use DirectX/Direct3D to take faster screenshots, and everyone was talking about GetFrontBufferData() and how wonderful it was.
I've pounded at it for a while but am starting to think they're using the term "screenshot" incorrectly... My call succeeds, but I never get a "screenshot".
So the question is, can you actually use GetFrontBufferData() to make a REAL screenshot of the whole desktop, or is it merely a way to read the pixels out of the front buffer WITHIN the confines of your d3d-device's drawing area?
(Upon success, I'd have expected to see the drawing area within my window do that old tv-in a tv-in a tv-in a tv-in a tv - kind of effect. I got nothing but black.)
Edit:
So, I was able to get a screenshot to work, but can't seem to put my image into the buffer for my app window.
At first, I thought this was because they were separate devices, but I've tried creating a second surface on the correct device and then manually copying the contents over. (Although I might be copying it wrong ((not important right now)) the call to the stretchrect still fails for the correct device.
Any idea why it won't let me apply this surface to my backbuffer???
D3DDISPLAYMODE          d3dDisplayMode;
D3DPRESENT_PARAMETERS   d3dPresentationParameters;

if( (d3d=Direct3DCreate9(D3D_SDK_VERSION))==NULL )
    exit(1);
D3DCAPS9 d3dcps;
d3d->GetDeviceCaps(D3DADAPTER_DEFAULT,D3DDEVTYPE_HAL,&d3dcps);
DWORD targets = d3dcps.NumSimultaneousRTs;
// TODO: ^ make a way for user to select one from this and put it into i
DWORD i=D3DADAPTER_DEFAULT;

if( d3d->GetAdapterDisplayMode(i,&d3dDisplayMode)==D3DERR_INVALIDCALL )
    exit(1);

ZeroMemory(&d3dPresentationParameters,sizeof(D3DPRESENT_PARAMETERS));//Fills a block of memory with zeros.
d3dPresentationParameters.Windowed = TRUE;
d3dPresentationParameters.Flags = D3DPRESENTFLAG_LOCKABLE_BACKBUFFER;
d3dPresentationParameters.BackBufferFormat = d3dDisplayMode.Format;//d3dDisplayMode.Format;//D3DFMT_A8R8G8B8;
d3dPresentationParameters.BackBufferCount = 1;
d3dPresentationParameters.BackBufferHeight = d3dDisplayMode.Height;
d3dPresentationParameters.BackBufferWidth = d3dDisplayMode.Width;
d3dPresentationParameters.MultiSampleType = D3DMULTISAMPLE_NONE;
d3dPresentationParameters.MultiSampleQuality = 0;
d3dPresentationParameters.SwapEffect = D3DSWAPEFFECT_DISCARD;
d3dPresentationParameters.hDeviceWindow = hwDesktop;
d3dPresentationParameters.PresentationInterval = D3DPRESENT_INTERVAL_DEFAULT;
d3dPresentationParameters.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT;

if( d3d->CreateDevice(i,D3DDEVTYPE_HAL,hwDesktop,D3DCREATE_SOFTWARE_VERTEXPROCESSING,&d3dPresentationParameters,&d3dcdev) != D3D_OK )
    exit(1);

if( d3dcdev->CreateOffscreenPlainSurface(d3dDisplayMode.Width,d3dDisplayMode.Height,D3DFMT_A8R8G8B8,D3DPOOL_SYSTEMMEM,&sfScrn, NULL) != D3D_OK )
    exit(1);

if( d3dcdev->GetFrontBufferData(0,sfScrn) != D3D_OK)
    exit(1);

// we now have a screenshot in sfScrn.
// let's render it to a separate device in our app window!
d3dPresentationParameters.hDeviceWindow = hwDrawArea;
if( d3d->CreateDevice(i,D3DDEVTYPE_HAL,hwDrawArea,D3DCREATE_SOFTWARE_VERTEXPROCESSING,&d3dPresentationParameters,&d3drdev) != D3D_OK )
    exit(1);
d3drdev->GetBackBuffer(0,0,D3DBACKBUFFER_TYPE_MONO,&sfBackBuffer);
if( d3drdev->CreateOffscreenPlainSurface(d3dDisplayMode.Width,d3dDisplayMode.Height,D3DFMT_A8R8G8B8,D3DPOOL_SYSTEMMEM,&sfTransfer, NULL) != D3D_OK )
    exit(1);

D3DLOCKED_RECT lockedRectScrn, lockedRectTransfer;
ZeroMemory(&lockedRectScrn, sizeof(D3DLOCKED_RECT));
ZeroMemory(&lockedRectTransfer, sizeof(D3DLOCKED_RECT));
if(sfScrn->LockRect(&lockedRectScrn,NULL,D3DLOCK_READONLY) != D3D_OK
    || sfTransfer->LockRect(&lockedRectTransfer,NULL,0) != D3D_OK )
    exit(1);
memcpy((BYTE*)lockedRectTransfer.pBits,(BYTE*)lockedRectScrn.pBits,lockedRectScrn.Pitch*d3dDisplayMode.Height);
sfScrn->UnlockRect();
sfTransfer->UnlockRect();

while(true)
{
    if(d3drdev != NULL)
    {
        d3drdev->Clear(0,NULL,D3DCLEAR_TARGET,D3DCOLOR_XRGB(75,0,0),1.0f,0);
        if(D3D_OK!=d3drdev->StretchRect(sfTransfer,NULL,sfBackBuffer,NULL,D3DTEXF_NONE))
        {
            MessageBox(NULL,"failed to use stretchrect","",0);
            exit(1);
        }
        if(d3drdev->BeginScene())
        {
            d3drdev->EndScene();
        }
        d3drdev->Present(NULL,NULL,NULL,NULL);
    }
}

Edit2:
Oh! So apparently you can't use StretchRect() on surfaces that are in D3DPOOL_SYSTEMMEM, but you must use GetFronBufferData() on D3DPOOL_SYSTEMMEM.

A: Yes. you can capture the Windows desktop using GetFrontBufferData. As proof I can offer this recent question where the poster had it working, except not when the desktop was using 16-bit colour. It might give you some insight in how to use it correctly.
But no, that's the not the "true purpose" of GetFrontBufferData. It's real purpose is to allow Direct3D games to capture screenshots of the game itself regardless of whether the game is windowed or fullscreen, and most importantly, whether or not the game is using multisampling or not.
GetFrontBufferData isn't designed to be a better method to take screenshots of the Windows desktop. It might happen to be faster than other methods, but that's not why it exists.


text:
Q: String search Regular expressions VB? In Excel VB I'm trying to search a string for a 4 digit number denoting a year, ie. "The man was born in the year 1986, it was a sunny day", I am trying to extract the "1986" from this string. It seems like using regular expressions would be my best option however I'm unfamiliar with them, is the regular expression for a 4 digit number something like "\d{4}" ?,
if I find that my string contains such a number is there an efficient way for getting the start and end point of the string for extraction? I have ideas on how to do it but they seem very inefficient, is there a fast way to find and extract this data?
pseudocode:
dim bool As boolean
bool = cells(d, 1).Value.contains(\d{4})

if bool then
   'extract string
end if


text:
Q: "System Policy prohibits use as a Hotspot" when trying to turn on WiFi hotspot (option grayed out) I'm using Ubuntu 20.04 on ThinkPad x230, W540, T440p, etc.
Sometimes (appears randomly) after a reboot, I try to click on "Turn on WiFi hotspot..." under WiFi settings, but it is greyed out and when I hover over it, it says "System Policy prohibits use as a hotspot".
Why is this?

A: reported here, try switching to another settings panel (ie "Network") and then back, it seems to enable the option again for most.

A: It's only periodically disabled; to re-enable simply click on the "Network" in the left pane - making sure the OS realises you have a network connection. Then go back to WiFi and voila you have the ability to create a WiFi HotSpot. You don't have to create a separate network for this.

A: This is also happened in my machine as well. So what I did is I have created hotspot network and connected via hidden network.
For that, Normal wifi setting will not give this setup. So
follow these instructions
1. Press alt+f2
2.You will see a popup window where you need to type follow command to get wifi setting window
nm-connection-editor

3.You need to press + icon to create a hotspot network

4.After that, You have to select WIFI option

*You need to change the mode to hotspot and SSID as you prefer

*Save the setting then open wifi setting

*select the network you have created

*Click connect to hidden network

*Select your network which you have created

*After you connect your hotspot you can see below like picture

Congrats you enable your hotspot


text:
Q: AttributeError: module 'fut' has no attribute 'Core' I'm pulling my hair out soon. I get the error:

File "/home/*****/PycharmProjects/Futbot _hako_ny/FUT/Central.py", line 27, in main
  core_class = fut.Core('******@hotmail.com', '*****', '*****', platform='ps4',sms=True, proxies=proxy,anticaptcha_client_key=captcha_key)  # Setting up core class
  AttributeError: module 'fut' has no attribute 'Core'

I know there is an attribute Core in the module fut. I tried:
print(fut)
<module 'fut' from '/home/*****/PycharmProjects/fut/fut/__init__.py'>

and I can see that it is using the correct module path. Everything was working fine, until I imported a self-made module into the core.py and added a print-statement. If I outcomment my import and small change to the core.py, then everything is working fine again.
Why does an import / small change breaks my program? Pycharm doesn't complain about any of my imports or code.
Any suggestions would be much appreciated.

A: I figured it out. The error was caused by circular dependency. My module "core.py" was importing the module "Central.py" and vice versa. In the fixed version, I moved the "import Central" into the function that was using it.


text:
Q: How can setup routing for Power BI via firewall in Azure In this scenario requirement is connecting to azure synapse and data factory which in public end point.
Public end point should be accessed through firewall in virtual network

A: You need to allow the relevant Microsoft Azure Datacenter IP's to connect through to the VNET. The relevant ranges will depend on your PowerBI instance's home location. If you log in to PowerBI online, click the ? and select "About PowerBI" you will get the box below and you can tell from the "Your data is stored in" attribute.

It is updated weekly but changes affecting the PowerBI don't seem to occur often, in fact, in the last 6 months this has been stable for us. We struggled to find the right range, so we set up a simple PowerBI report that connects to an open Azure storage account with logging enabled and then refreshed the report from PowerBI service and looked in the storage account's firewall logs to see the IP the requests are originating from. This helped us to narrow down the IP's we needed to white list.


text:
Q: How can i access session in different jspx? I'm new to jspx and I'm not sure how I would do this. I have created a model-view-controller and have created a session in controller. Once the user has logged in, it creates the session.
HttpSession session = request.getSession();
session.setAttribute("user", username);

How can I access and display the username in the welcome.jspx page, so it would say
hello username

A: Use EL to access it.
hello ${user}

To prevent XSS attacks by username, show it using JSTL <c:out> so that XML special characters are escaped:
<jsp:root xmlns:c="http://java.sun.com/jsp/jstl/core" ...>
...

hello <c:out value="${user}" />

A: Try something like this (For JSP):
<%
  String username = (String)session.getAttribute("user");
  out.println("<b>Welcome " + username + "!</b>");
%>

I have used scriptlet tag here. You can study about it  from here .
(may be it could help someone else.)


text:
Q: Altering a variable within a .tflite model in Xcode? I'm trying to implement the Neural Style Transfer model by https://arxiv.org/pdf/1610.07629.pdf in an iOS app. The paper uses this conditional instance norm layer to allow a single model to learn multiple styles and also combine the styles.
Here is my code for it:
class ConditionalInstanceNorm(tf.keras.layers.Layer):
  def __init__(self, scope_bn, y1, y2, alpha):
    super(ConditionalInstanceNorm, self).__init__()
    self.scope_bn = scope_bn
    self.y1 = y1
    self.y2 = y2
    self.alpha = alpha

  def build(self, input_shape):
    self.beta = self.add_weight(name="beta"+self.scope_bn, shape=(self.y1.shape[-1], input_shape[-1]), initializer=betaInitializer, trainable=True)
    self.gamma = self.add_weight(name="gamma"+self.scope_bn, shape=(self.y1.shape[-1], input_shape[-1]), initializer=gammaInitializer, trainable=True)

  def call(self, inputs):
    mean, var = tf.nn.moments(x=inputs, axes=[1,2], keepdims=True)
    beta1 = tf.matmul(self.y1, self.beta)
    gamma1 = tf.matmul(self.y1, self.gamma)
    beta2 = tf.matmul(self.y2, self.beta)
    gamma2 = tf.matmul(self.y2, self.gamma)
    beta = self.alpha*beta1 + (1. - self.alpha)*beta2
    gamma = self.alpha*gamma1 + (1. - self.alpha)*gamma2
    x = tf.nn.batch_normalization(x=inputs, mean=mean, variance=var, offset=beta, scale=gamma, variance_epsilon=1e-10)
    return x

It requires me to pass in 3 hyper-parameters: y1, y2, and alpha. Each style has a unique y value (y1 and y2 are the different styles to allow combining of styles). Alpha determines the strength of influence of each style.
In python, the way I switch between different combinations of styles is by accessing each layer, identify the conditional instance norm layers then change the y1, y2, and alpha values stored:
  for layer in filter(lambda x: "conditional_instance_norm" in x.name, model.layers):
    layer.y1 = y1
    layer.y1 = y2
    layer.alpha = alpha

How can I do this with a .tflite model in swift? Right now I can run the model but it is stuck with the y1, y2, and alpha values it was initialised with.

A: I found a way of being able to input the values by altering the structure of my model in python to include 3 additional inputs - y1, y2, and alpha, like this:
def ImageTransformNetwork():
  inputs = Input(shape=(dim,dim,3))
  y1 = Input(shape=(13), batch_size=1)
  y2 = Input(shape=(13), batch_size=1)
  alpha = Input(shape=(1), batch_size=1)
  x = PadConvBatch(x=inputs, kernel_size=9, scope_bn="1", y1=y1, y2=y2, alpha=alpha)
  x = PadConvBatch(x=x, filters=64, strides=2, scope_bn="2", y1=y1, y2=y2, alpha=alpha)
  x = PadConvBatch(x=x, filters=128, strides=2, scope_bn="3", y1=y1, y2=y2, alpha=alpha)
  x = Resblock(x=x, scope_bn1="4", scope_bn2="5", y1=y1, y2=y2, alpha=alpha)
  x = Resblock(x=x, scope_bn1="6", scope_bn2="7", y1=y1, y2=y2, alpha=alpha)
  x = Resblock(x=x, scope_bn1="8", scope_bn2="9", y1=y1, y2=y2, alpha=alpha)
  x = Resblock(x=x, scope_bn1="10", scope_bn2="11", y1=y1, y2=y2, alpha=alpha)
  x = Resblock(x=x, scope_bn1="12", scope_bn2="13", y1=y1, y2=y2, alpha=alpha)
  x = PadConvBatch(x=x, filters=64, strides=0.5, scope_bn="14", y1=y1, y2=y2, alpha=alpha)
  x = PadConvBatch(x=x, filters=32, strides=0.5, scope_bn="15", y1=y1, y2=y2, alpha=alpha)
  x = tf.pad(x, [[0,0], [4,4], [4,4], [0,0]], "REFLECT")
  x = Conv2D(filters=3, kernel_size=9, strides=1, activation='sigmoid', kernel_initializer=initializer)(x)
  model = Model(inputs=[inputs, y1, y2, alpha], outputs=x)
  return model

Thus after converting this to a tflite model, I can put in my variables like such:
try self.imageTransformInterpreter.copy(inputRGBData, toInputAt: 3)
try self.imageTransformInterpreter.copy(Data(bytes: yArray1, count: 52), toInputAt: 0)
try self.imageTransformInterpreter.copy(Data(bytes: yArray2, count: 52), toInputAt: 2)
try self.imageTransformInterpreter.copy(Data(buffer: alphaBuffer), toInputAt: 1)


text:
Q: http post method problem In my application I'm using outpost method to send data to web service which is in .net.Now when i send string with spaces or special characters it takes the string with e.g. test string would display like test+string.
I'm using httpDefaultClient with nameValuePair to send data...i've used UrlEncode function to encode my string but still result is the same...
Please help me...
Here is my code
//web service call
                HttpClient client=new DefaultHttpClient();
                HttpPost request = new HttpPost();
                request.setURI(new URI(url2));

                List<NameValuePair> nameValuePairs=new ArrayList<NameValuePair>();
                //  nameValuePairs.add(new BasicNameValuePair("CreateHotSpots", value))
                nameValuePairs.add(new BasicNameValuePair("sKey",""+globalClass.getUser_key()));
                nameValuePairs.add(new BasicNameValuePair("sLAKE",encodedlakename));
                if(!(DragAndDropPinActivity.point.isEmpty())){
                    nameValuePairs.add(new BasicNameValuePair("sLAT",""+DragAndDropPinActivity.point.get(0)));
                    nameValuePairs.add(new BasicNameValuePair("sLon",""+DragAndDropPinActivity.point.get(1)));

                }
                else
                {
                    url2=url2.concat("&sLAT="+""+myLatitude);
                    url2=url2.concat("&sLon="+""+myLongitude);

                }

                nameValuePairs.add(new BasicNameValuePair("sDesc",encodedDesc));
                nameValuePairs.add(new BasicNameValuePair("sSpeciesofFish",encodedFishSpecies));
                nameValuePairs.add(new BasicNameValuePair("sBaitUsed",encodedbUsed));
                nameValuePairs.add(new BasicNameValuePair("sWeatherInformation",encodedwInfo));
                nameValuePairs.add(new BasicNameValuePair("season",encodedlseason));
                nameValuePairs.add(new BasicNameValuePair("sDesc",""+encodedDesc));
                if(share)
                {
                    nameValuePairs.add(new BasicNameValuePair("sShareInfo","true"));
                }
                else
                {
                    nameValuePairs.add(new BasicNameValuePair("sShareInfo","false"));
                }

                Log.e("name value pairs",""+nameValuePairs.toString());
                UrlEncodedFormEntity entity_st=new UrlEncodedFormEntity(nameValuePairs,"UTF-8");
                request.setEntity(entity_st);

                HttpResponse response = client.execute(request);
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {

                    Responce=EntityUtils.toString(resEntity);
                    Log.i("responce ======",""+Responce);

                }

            }
            catch (Exception e) {
                e.printStackTrace();
                String message=e.getMessage();
                Log.e("meaasge with erroe",message);
            }

            return Responce;
        }

A: step 1
You have specified a "UTF-8" encoding in
UrlEncodedFormEntity entity_st=new UrlEncodedFormEntity(nameValuePairs,"UTF-8");

Try to change it to
UrlEncodedFormEntity entity_st=new UrlEncodedFormEntity(nameValuePairs);

step 2
I noticed that the strings you are adding to the request are called encodeXXXX
Does this mean that you are encoding them before adding them to the ValuePairs?
If so, stop doing this and keep them as normal strings.


text:
Q: Python Django rest-framework serializer omitting field I'm facing a problem using python2.7 with django rest-framework. When I serialize my JSON data, a field is omitted by the serializer and I don't understand why. Here is some details.
The missing field is "country". When I'm doing POST or PUT requests on /campaigns/:id
class CampaignSerializer(serializers.HyperlinkedModelSerializer):
    created_by = UserFullSerializer(read_only=True)
    country = CountrySerializer(read_only=True)

    class Meta:
        model = Campaign
        fields = ('id', 'created_by', 'name', 'media', 'status', 'begin', 'end', 'country')

class CampaignFullSerializer(serializers.HyperlinkedModelSerializer):
    client = ClientSerializer(read_only=True)
    collection = CollectionSerializer(read_only=True)
    created_by = UserFullSerializer(read_only=True)
    updated_by = UserFullSerializer(read_only=True)
    channels = ChannelSerializer(read_only=True, many=True)
    country = CountrySerializer(read_only=True)

    class Meta:
        model = Campaign
        fields = ('id',
                  'client',
                  'name',
                  'media',
                  'status',
                  'begin',
                  'end',
                  'created_at',
                  'created_by',
                  'updated_at',
                  'updated_by',
                  'collection',
                  'channels',
                  'country')

class CountrySerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Country
        fields = ('id', 'name', 'code')

class Country(models.Model):
    name = models.CharField(max_length=255)
    code = models.CharField(max_length=255)

class Campaign(models.Model):
    name = models.CharField(max_length=255)
    media = models.IntegerField(choices=constant.MEDIA_CHOICES, default=0)
    status = models.IntegerField(choices=constant.STATUS_CHOICES, default=2)
    created_at = models.DateTimeField(auto_now_add=True)
    created_by = models.ForeignKey(User, blank=True, null=True, related_name="created_by")
    updated_at = models.DateTimeField(auto_now_add=True, blank=True, null=True)
    updated_by = models.ForeignKey(User, blank=True, null=True, related_name="updated_by")
    client = models.ForeignKey(client.Client)
    begin = models.DateField(blank=True, null=True)
    end = models.DateField(blank=True, null=True)
    collection = models.ForeignKey(collection.Collection, blank=True, null=True)
    country = models.ForeignKey(country.Country, blank=True, null=True)
    mediaplan = models.ForeignKey(mediaplan.Mediaplan, blank=True, null=True, default=None)
    channels = models.ManyToManyField(channel.Channel)

When I'm doing POST on /campaign/id with the following JSON, everything works except the country field.
{
    ...
    "channels": [],
    "country": {
        "id": 74,
        "name": "France",
        "code": "FR"
}

On the controller side when I print the request.data I got all the fields. I'm not overriding the create method of the controller.
{
    ...
    u'country': {u'code': u'AL', u'id': 3, u'name': u'Albania'}
}

My controller looks like:
class CampaignViewSet(viewsets.ModelViewSet):
    queryset = Campaign.objects.all()
    serializer_class = CampaignSerializer

    def create(self, request):
        logger.info(request.data)
        return super(CampaignViewSet, self).create(request, *args, **kwargs)

I tried to override the create method of my CountrySerializer and when I print the content of validated_data, the country field is missing in the OrderedDict..
class CountrySerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Country
        fields = ('id', 'name', 'code')

        def create(self, validated_data):
            logger.info(validated_data)

I'm really lost, I can't find my mistake, maybe you will. Thanks for your time.

A: Your CountrySerializer is read only as a nested serializer by default (per http://www.django-rest-framework.org/api-guide/relations/#nested-relationships) so you have to override the create/update method of the Campaign serializer for POST/PUT. You've tried to override it on the Country serializer instead.


text:
Q: White page when deploying Symfony2 Project After I finished my project of symfony2 on windows I wanted to deploy it on a digitalocean server with Linux-Ubuntu OS. But there are some problems I can't figure them out. Please help me soon.
I uploaded the web folder files to folder html on server and other files (src , app , bin, vendor) to www folder. I also followed the instructions on config.php and solved the problems. But yet:
1- When I trying to type url : ip_address/app.php/ on browser a white page comes. No page and No error!
2- When I want to clear the cache in production env using the putty this error happens. ( Unable to write in the "C:/wamp/www/my-project/app/cache/prod" directory) but there is no such problem when clearing on localhost (I think this problem is because of transferring the project from windows to linux)
Please help me.

A: You probably have some errors (maybe cache directory).
For testing open the file web/app_dev.php and comment this:
/*if (isset($_SERVER['HTTP_CLIENT_IP'])
    || isset($_SERVER['HTTP_X_FORWARDED_FOR'])
    || !in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', 'fe80::1', '::1'))
) {
    header('HTTP/1.0 403 Forbidden');
    exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}
*/

Now you can access your page via ip_address/app_dev.php/ and see errors. When you finish, don't forget to uncomment this.
If you have problems with cache, then I suggest you to upload code without cache directory. Then create this directory in the server and give it right permissions.


text:
Q: Jersey rest service not returning XMLresponse I am building a rest API using Jersey where XML and JSON outputs are allowed depending on what format client prefers(using Accept header).The service sends the below class as an output which looks like this
@XmlRootElement
public class ProjectDetails{

    private List<Attachment> attachments;
    private Map<String, List<Attachment>> imageCategory;

    @XmlTransient
    public List<Attachment> getAttachments() {
        return attachments;
    }

    public void setAttachments(List<Attachment> attachments) {
        this.attachments = attachments;
    }

    public Map<String, List<Attachment>> getImageCategory() {
        if(attachments == null || attachments.size() == 0){
            return null;
        }

        Map<String, List<Attachment>> map = new HashMap<String, List<Attachment>>();
        for (Attachment img : attachments){
            String key = img.getCategory();
            if(BaseUtil.hasText(key)){
                List<Attachment> values = map.get(key);
                if (values == null){
                    values = new ArrayList<Attachment>();
                }
                values.add(img);
                map.put(key, values);
            }
        }

        this.imageCategory = map ;
        return imageCategory;
    }

    public void setImageCategory(Map<String, List<Attachment>> imageCategory) {
        this.imageCategory = imageCategory;
    }
}

I don't want attachments field as an output so marked it with @XmlTransient rather I want to form a Map using the attachments field and send it as an output.
In case of JSON format, I am getting the correct response.But in case of XML, I am not getting any output when I hit the service.
I think it is related to this Map field because if I remove Map field and add some other field like String then I get that field in response.
Please let me know how to resolve this.
Update:
After some googling, i found XmlAdapter solution and implemented as below
public class MapAdapter extends
        XmlAdapter<MapAdapter.AdaptedMap, Map<String, List<Attachment>>> {

    public static class AdaptedEntry {
        public String key;
        public List<Attachment> value = new ArrayList<Attachment>();
    }

    public static class AdaptedMap {
        List<AdaptedEntry> entries = new ArrayList<AdaptedEntry>();
    }

    @Override
    public AdaptedMap marshal(Map<String, List<Attachment>> map)
            throws Exception {
        AdaptedMap adaptedMap = new AdaptedMap();

        for (Entry<String, List<Attachment>> entry : map.entrySet()) {
            AdaptedEntry adaptedEntry = new AdaptedEntry();
            adaptedEntry.key = entry.getKey();
            adaptedEntry.value = entry.getValue();
            adaptedMap.entries.add(adaptedEntry);
        }
        return adaptedMap;
    }

    @Override
    public Map<String, List<Attachment>> unmarshal(AdaptedMap adaptedMap)
            throws Exception {
        List<AdaptedEntry> adapatedEntries = adaptedMap.entries;
        Map<String, List<Attachment>> map = new HashMap<String, List<Attachment>>(
                adapatedEntries.size());

        for (AdaptedEntry adaptedEntry : adapatedEntries) {
            map.put(adaptedEntry.key, adaptedEntry.value);
        }
        return map;
    }

And then
@XmlJavaTypeAdapter(MapAdapter.class)
    public Map<String, String> getImageCategory() {

But still it's not working..Anything I missed?

A: I have used your ProjectDetails class a little bit changes I've made, and it provides response for both XML and JSON. Can you try this?
@XmlRootElement
public class ProjectDetails {
private List<Attachment> attachments;
private Map<String, ArrayList<Attachment>> imageCategory;

@XmlTransient
public List<Attachment> getAttachments() {
    return attachments;
}

public void setAttachments(List<Attachment> attachments) {
    this.attachments = attachments;
}
@XmlJavaTypeAdapter(MapAdapter.class)
public Map<String, ArrayList<Attachment>> getImageCategory() {
    if(attachments == null || attachments.size() == 0){
        return null;
    }
    Map<String, ArrayList<Attachment>> map = new HashMap<String, ArrayList<Attachment>>();
    for (Attachment img : attachments){
        String key = img.getCategory();
        if(!key.equals("")){
            ArrayList<Attachment> values = map.get(key);
            if (values == null){
                values = new ArrayList<Attachment>();
            }
            values.add(img);
            map.put(key, values);
        }
    }

    this.imageCategory = map ;
    return imageCategory;
}

public void setImageCategory(Map<String, ArrayList<Attachment>> imageCategory) {
    this.imageCategory = imageCategory;
}

}

And the Adapter class  you can use the following
public class MapAdapter extends XmlAdapter<MapElement[], Map<String, ArrayList<Attachment>>>{
public MapElement[] marshal(Map<String, ArrayList<Attachment>> arg0) throws Exception {
    MapElement[] mapElements = new MapElement[arg0.size()];
    int i = 0;
    for (Map.Entry<String, ArrayList<Attachment>> entry : arg0.entrySet()){
        mapElements[i++] = new MapElement(entry.getKey(), entry.getValue());
    }
    return mapElements;
}

public Map<String, ArrayList<Attachment>> unmarshal(MapElement[] arg0) throws Exception {
    Map<String, ArrayList<Attachment>> r = new HashMap<String, ArrayList<Attachment>>();
    for (MapElement mapelement : arg0)
        r.put(mapelement.key, mapelement.value);
    return r;
}

}

I've changed the MapElement also
public class MapElement {
@XmlElement
public String key;
@XmlElement
public ArrayList<Attachment> value;

private MapElement() {
}

public MapElement(String key, ArrayList<Attachment> value) {
    this.key = key;
    this.value = value;
}
}

And the Attachement class should have getter setter methods
public class Attachment {
public String getCategory() {
    return category;
}
public void setCategory(String category) {
    this.category = category;
}
private String category;
public Attachment(String cat){
    this.category = cat;
}

}


text:
Q: Add specific row data for a specific column value
Hi everyone,
I'm new to python.
When I find a specific value in the column comm_rate, I want to add the utility_name and zip to print out, like the example below. Any help will be highly appreciated.
Here is the link for the CSV file:
The highest rate is:
Napakiak Ircinraq Power Co (99634, AK) - $0.839779005525
Here is my code and CSV image attached:
import csv

def pronmpt_filename():
    filename = input("Please enter the data file: ")
    return filename

def comm_rate():
    commR_list = []
    with open(pronmpt_filename(), "r") as my_csv:
        reader = csv.DictReader(my_csv, delimiter=",")
        for row in reader:
            commR = row["comm_rate"]
            if commR != None and commR != "":
                commR_list.append(float(row["comm_rate"]))

    avg_commR = sum(commR_list) / len(commR_list)
    print("")
    print("The average commercial rate is: ", avg_commR)
    print("")
    print("The highest rate is: \n", max(commR_list))
    print("")
    print("The lowest rate is: \n", min(commR_list))

A: You can do it using python zip function. Here I show you the example (I will be using pandas to read the csv file, you can choose as per your requirement. But I will recommend pandas for this type of problems):
import pandas as pd
read_file = pd.read_csv("filename.csv")
zipped_result = [ (f, i) for f, i in zip(read_file["comm_rate"], read_file["utility_name"])]

for i,j in zipped_result:
    print(f"The highest rate is:  {j} -  {i}.")


text:
Q: Establishing connection of SQL Server 2008 with VS2012 project via web.config file I'm trying to connect my database from my SQL Server to my asp.net project through the web.config file. I found code like this which should be able to connect my SQL Server and ASP.net project together properly. However after adding this code, I got this error.
This is my SQL Server connection string that is supposed to be place in web.config:
<connectionStrings>
   <add name="MyConnectionString"
        connectionString="Data Source=sergio-desktop\sqlexpress;Initial
                          Catalog=MyDatabase;User ID=userName;Password=password"
        providerName="System.Data.SqlClient" />
</connectionStrings>

And this is the error

I'm also not very sure if the syntax of my connection string to establish connection between the two is correct.

A: As the error suggests, the connection element should not go in system.web section. it should go in configuration section of your web.config
as
<configuration>
<connectionStrings>
---


text:
Q: Is it possible to POST one specific item from a List using Thymeleaf? In my Spring Boot app i have the following RequestMapping:
@GetMapping("/test")
public String get(Model model) {
    List<CustomItem> items = itemService.findAll();
    model.addAttribute("items", items);
    return "test";
}

I'm displaying these items in a simple HTML table (one row for one item).
I'd like a add a button to each row that submits only the corresponding CustomItem to an endpoint something like this:
@PostMapping("/test")
public String post(CustomItem item) {
    // doing something with item
    return "redirect:/test";
}

What i've tried is to create a separate form for each row:

   <form th:object="${items[__${stat.index}__]}" th:action="@{/test}" method="post">
    <input type="text" th:field="${items[__${stat.index}__].someField}">
    <button type="submit">Submit</button>
   </form>

But i'm receiving the following error when navigating to the page:

Neither BindingResult nor plain target object for bean name 'items[0]'
  available as request attribute

I've tried the following as well:

   <form th:object="${item}" th:action="@{/test}" method="post">
    <input type="text" th:field="*{someField}">
    <button type="submit">Submit</button>
   </form>

In this case the error is the following:

Neither BindingResult nor plain target object for bean name 'item'
  available as request attribute

I cannot figure out what's wrong with my approach, so i'd really appreciate any advice.
EDIT:
As @StefanEmanuelsson suggested i've tried omitting the th:object attribute:

   <form th:action="@{/test}" method="post">
    <input type="text" th:field="${items[__${stat.index}__].someField}">
    <button type="submit">Submit</button>
   </form>

This way the page loads just fine, but on submitting the form the value of someField in the received(?) CustomItem in the controller is null.

A: This worked for me:
Instantiate item in the controller and set to the model:
@GetMapping("/test")
public String get(Model model) {
    List<CustomItem> items = itemService.findAll();
    model.addAttribute("items", items);
    model.addAttribute("item", new CustomItem());
    return "test";
}

HTML:

            <form th:action="@{/test}" method="post" th:object="${item}">

            <input type="hidden" th:value="${i.id}" name="id" />
                <input type="hidden" th:value="${i.someField}" name="someField" />
                <button type="submit" name="action" value="remove">OK</button>
            </form>

And create a method in controller to handle the item:
@PostMapping("/test")
    public String test(@ModelAttribute CustomItem item,HttpServletRequest request) {
        doStuff(item);
    }

A: I've managed to solve this problem by simply using th:value and name attributes instead of th:field:

   <form th:action="@{/test}" method="post">
    <input type="text" th:value="${item.someField}" name="someField">
    <button type="submit">Submit</button>
   </form>


text:
Q: this is really annoying me how to remove all syntax colors of vim 7+ Im using centos 5.5 and installed vim 7
i defined syntax off in vimrc , and it removed me most of the syntax coloring , but i still
have colors when i move to curly braces , and when i search for string in source its paint me the result with yellow , all so when i do code completion its also with colors
how do i remove all colors from vim i want it to be like old vi.

A: Write this stuff in ~/.vimrc

*

*set nohlsearch - disables highlighted search

*let g:loaded_matchparen=1 - disable brace/paren/bracket matching

A: Remove the vi alias in your shell.
unalias vi

A: You might want to try disabling syntax different way as :syntax=off doesn't turn off all the colors. Try using following :set syntax=off or i believe :set syntax= should work as well. This should disable all the colors, including Line number.
For follow up question regarding the colors of line numbers (if anyone want's to disable just that):
you can disable the colors of the Line numbers by doing following: :hi LineNr ctermfg=white
(really not disabling, just making it white)
You can use :hi to change the colors of mostly anything in VI to make them white or any color, really.


text:
Q: Firebase build error for multiple build variants on Android Instant App I am adding Firebase to an existing app with 3 buildTypes (debug, staging and release). There's also 2 flavors (live and mock), but I am enabling mock only for debug builds:
android.variantFilter { variant ->
    if ((variant.buildType.name.equals('release') || variant.buildType.name.equals('staging'))
            && ((variant.getFlavors().get(0).name.equals('mock')))) {
        variant.setIgnore(true);
    }
}

So there are 3 applicationIds: me.app (release), me.app.debug(debug) and me.app.staging (staging). As evident, there's only one app for debug, although there are 2 variants (debugLive and debugMock)
On Firebase, I created 1 project and added 3 apps - 1 for each application ID. I did not give a SHA1 key for any of these apps as of now. I downloaded the google-services.json and placed it in the base-feature module's root directory.
I am unable to sync project with Gradle now:
More than one variant of project :myapp-base-feature matches the consumer attributes:
  - Configuration ':myapp-base-feature:mockDebugApiElements' variant android-aidl:
      - Found artifactType 'android-aidl' but wasn't required.
      - Required com.android.build.api.attributes.BuildTypeAttr 'debug' and found compatible value 'debug'.
      - Found com.android.build.api.attributes.VariantAttr 'mockDebug' but wasn't required.
      - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' and found compatible value 'Aar'.
      - Required mocking 'mock' and found compatible value 'mock'.
      - Required org.gradle.usage 'java-api' and found compatible value 'java-api'.
  - Configuration ':myapp-base-feature:mockDebugApiElements' variant android-classes:
      - Found artifactType 'android-classes' but wasn't required.
      - Required com.android.build.api.attributes.BuildTypeAttr 'debug' and found compatible value 'debug'.
      - Found com.android.build.api.attributes.VariantAttr 'mockDebug' but wasn't required.
      - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' and found compatible value 'Aar'.
      - Required mocking 'mock' and found compatible value 'mock'.
      - Required org.gradle.usage 'java-api' and found compatible value 'java-api'.
  - Configuration ':myapp-base-feature:mockDebugApiElements' variant android-manifest:
      - Found artifactType 'android-manifest' but wasn't required.
      - Required com.android.build.api.attributes.BuildTypeAttr 'debug' and found compatible value 'debug'.
      - Found com.android.build.api.attributes.VariantAttr 'mockDebug' but wasn't required.
      - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' and found compatible value 'Aar'.
      - Required mocking 'mock' and found compatible value 'mock'.
      - Required org.gradle.usage 'java-api' and found compatible value 'java-api'.
  - Configuration ':myapp-base-feature:mockDebugApiElements' variant android-renderscript:
      - Found artifactType 'android-renderscript' but wasn't required.
      - Required com.android.build.api.attributes.BuildTypeAttr 'debug' and found compatible value 'debug'.
      - Found com.android.build.api.attributes.VariantAttr 'mockDebug' but wasn't required.
      - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' and found compatible value 'Aar'.
      - Required mocking 'mock' and found compatible value 'mock'.
      - Required org.gradle.usage 'java-api' and found compatible value 'java-api'.
  - Configuration ':myapp-base-feature:mockDebugApiElements' variant jar:
      - Found artifactType 'jar' but wasn't required.
      - Required com.android.build.api.attributes.BuildTypeAttr 'debug' and found compatible value 'debug'.
      - Found com.android.build.api.attributes.VariantAttr 'mockDebug' but wasn't required.
      - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' and found compatible value 'Aar'.
      - Required mocking 'mock' and found compatible value 'mock'.
      - Required org.gradle.usage 'java-api' and found compatible value 'java-api'.

A: Downgrade your Google Service to 3.2.1
it is a known bug with flavors and submodules for 3.3.1 at least, probably 3.3.+
  dependencies {
        classpath 'com.android.tools.build:gradle:3.1.2'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.2.31"
        classpath 'com.google.gms:google-services:3.2.1'
        classpath 'io.fabric.tools:gradle:1.25.4'
    }


text:
Q: openssl elliptic curves I have an elliptic curve EC and I need to find such an point G of EC which coordinate is the smallest non-negative integer of all points on the curve. I need it for an implementation of ECOH hashing algorithm.
I was trying to use openssl to achieve this goal but so far I haven't figure out how to find such a point. I was trying to do this:
EC_POINT *G = EC_POINT_new(ec);
for(int i = 1; i < 1024; i++)
{
    itoa(i, str, 10);
    BN_dec2bn(&x, str);
    EC_POINT_set_affine_coordinates_GFp(ec, G, x, y, ctx);
    if(EC_POINT_is_on_curve(ec, G, ctx))
        printf("%s\n", str);
}

But it only checks whether the point with the coordinates of (x, y) is on the curve or not.
How can I find it?

A: First, find a generator if ec did not provide one. I suppose you want generator with the smallest x-coordinate. You can do something like this:
// Suppose you've found a generator point G, and a BIGNUM context bn_ctx
// has been created and initialized

BIGNUM x, y, x_min, y_min;
BN_init(&x); BN_init(&x_min);
BN_init(&y); BN_init(&y_min);

EC_POINT *P = EC_POINT_new(ec);
EC_POINT_copy(P,G);
EC_POINT_get_affine_coordinates_GFp(ec,P,x_min,y_min,bn_ctx);
do{
    EC_POINT_add(ec,P,P,G,bn_ctx);
    EC_POINT_get_affine_coordinates_GFp(ec,P,x,y,bn_ctx);
    if (x < x_min) {
        BN_copy(x_min, x);
        BN_copy(y_min, y);
    }
}while(!EC_POINT_is_at_infinity(ec,P));

Then you'll have your generator (x,y) with smallest x-coordinate.
As to how to find a generator in the first place, that's another story.

A: Instead of using EC_POINT_set_affine_coordinates_GFp, which requires both x and y, use EC_POINT_set_compressed_coordinates_GFp, which instead of a y takes a y_bit denoting which of the two y values (even or odd) to use for a given x (if the x is within the curve's domain).
Then you should be able to just loop through the first few x to find the coordinate with the smallest x, just as you're attempting to do.


text:
Q: Why My Program works perfectly when it should have generated a core dump because of dangling pointer? I works on recommendation system. And my program contains the following code:
#include<vector>
using namespace std;
#define MAX_KEYWORD_NUM 2048
struct keyword_t
{
    char* str;
    int* p;
    //other stuff
};
class Myclass
{
public:
    bool add_keyword(keyword_t &keyword);
    int getValueFromConfigurationFile(const char *);
    bool reset()
private:
    vector<keyword_t>_keywords_vec;
    vector<keyword_t*>_pkeywords_vec;
    Myclass();
    //other stuff
};
Myclass::Myclass()
{
    _keywords_vec.reserve(MAX_KEYWORD_NUM);
}
bool Myclass::reset()
{
    _pkeywords_vec.clear();
    _keywords_vec.clear();
}
bool Myclass::add_keyword(keyword_t& keyword)
{
    int limit = getValueFromConfigurationFile("limit");
    int _keywords_num = _keywords_vec.size();
    if (_keywords_num >= limit)
    {
        return false;
    }
    _keywords_vec.push_back(keyword);
    keyword_t* p_kw = &_keywords_vec[_keywords_num];
    _pkeywords_vec.push_back(p_kw);
    return true;
}

I define an object of Myclass in a thread and this thread will continually process incoming requests using this object.
Obviously, there is a potential problem in function add_keyword. That is if limit is greater than MAX_KEYWORD_NUM, _keywords_vec will be reallocated and all previous elements will probably be in different memory address. So, the pointers previously pushed into _pkeywords_vec will be dangling pointers and this will probably cause a core dump.
I do several experiments on it. However I got conflicting results.
Experiment A:
set the "limit" in configuration file to :3000, start the program, and it soon generates a core dump within one or two minutes.
Experiment B:
set the "limit" in configuration file to :2048, start the program, and after several minutes, change it to 3000. it also soon generates a core dump.
Experiment C:
set the "limit" in configuration file to :2048, start the program, and after some six hours, change it to 3000. it DO NOT generate any core dump and works perfectly well even for several days. I have make sure that limit has been changed to 3000 in this case.
All the experiments can be replicated.
How to explain Experiment C? Since Experiment C has been replicated thousands of times (different random requests), it is not likely that this is only undefined behavior. The possibility to generate core dump is obviously greater in Experiment A and B. So there should be something different between A\B and C.
Thanks.


text:
Q: Perform numpy product over non-zero elements of a row I have a 2d array r. What I want to do is to take the product of each row (excluding the zero elements in that row). For example if I have:
r = [[1 2 0 3 4],
     [0 2 5 0 1],
     [1 2 3 4 0]]

Then what I want is to have another 2d array result such that:
result = [[24],
          [10],
          [24]]

How can I achieve this using numpy.prod?

A: I think I figured it out:
np.prod(r, axis = 1, where = r > 0, keepdims = True)

Output:
array([[24],
[10],
[24]])


text:
Q: Sizzle JS how does it work? I was looking into the sizzle.js source code for a school project, and I noticed something strange. At the bottom of the code there is this line of code saying:
window.Sizzle = Sizzle;

But i can't find anything in the code saying anything about a:
var Sizzle = .....

The only thing i find that would resemble the Sizzle variable would be:
function Sizzle( selector, context, results, seed ) {

Now for my question. Is it possible for a function to act as an object like this? Or is it something that I've missed?

A: Yes, a function is itself a Javascript object and can be assigned to some other variable.


text:
Q: How should i set up my source folder? I have /src/main/ with all my code (i also have /src/online, /src/prvlibs, /src/test, etc) but now i am thinking about moving a few non active projects out of the folder. Sure i could go in and delete all objs, (some) project files, etc so it doesnt take 200mb of generated data. But i think it might be nice for only 20projects or less instead of dozen of prototypes that aren't throwaway test.
I use git for source control (but i'm sure all scm do the same thing). They dislike files are missing and if i delete them they aren't easy to browse. I like how i can commit all of my source by going to /src/main and commiting. And i can push all of them just as easily. But moving folders (to my external HD and keep history) is the problem.
Should i have every folder have its own repo? or is there some kind of workaround i can use? If every folder has its own repo is there an easy way to push all my folders to my HD (or website) for backup?

A: You should not keep all your projects (not even the experiments) under the same version control repository. Yes, you should have one repository for each project.
As to the pushing, write down a small process that you follow when you work on a project, include a push in it, and make provisions for backup.
Private repositories in public GIT sites (like GitHub) are an easy way to backup to the cloud using a simple process.
I'm paranoid about version control because I had really bad things happen when I wasn't. My process for an ongoing project is:

*

*Commit frequently.

*Push to central repository when a feature is complete or before taking a break.

*Backup working directory after a session.

*Backup central repository.

*Pull in working directories under other OSs or other workstations, test, fix, and repeat the above.

*Push to bitbucket.


text:
Q: css every n-th img in new row I have a react component and I would like to display inline-block 3 photos in a row with it's names under each photo, and every next 3 elements under (in new row) and so on...
I think I need to use something with:nth-child(3n+1) but something goes wrong...
const Photos=(props)=>{
    return(

{props.memoriesName}

    )
}

export default Photos

Could you please tell me how should css look like?

A: wrap all photos components in a div then style div with grid box like this:

   <Photos />
   <Photos />
   <Photos />

and css:
.parent {
    display:grid;
    grid-template-columns:auto auto auto;
}


text:
Q: When player jumps: scene moves down, player stays at place like Doodle Jump I am working on a game like doodle jump.
But when the player jumps above the screen, the player should stay at the edge of the screen and instead the objects will move downwards so it looks like the player i still moving upwards.
But how do I do this?
This is what I tried:
  if player.position.y > -0.35 * frame2.size.height{

        grond.physicsBody?.applyImpulse(CGVectorMake(0, -player.physicsBody?.velocity.dy))
        player.position.y = -0.35 * frame2.size.height
    }

But this gives error: operand of postfix ! should have optional type, type is CGFloat.

A: CGVectorMake takes two CGFloats. Optional chaining will yield the same type, but wrapped in an optional so you need to unwrap it :
CGVectorMake(0, (-player.physicsBody?.velocity.dy)!))


text:
Q: I created a custom view by subclassing SearchView. How can I reference in it XML now? I programmatically creating a custom view by extending the AppCompat SearchView. How do I reference this class in my XML? I cannot use the fully qualified name because I am using different product flavors with gradle that have different package names. Specifically, app:actionViewClass=".views.EventSearchView" causes a ClassNotFoundException
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".activities.MainActivity">
    <item
        android:id="@+id/action_search"
        android:title="@string/action_search"
        android:icon="@drawable/ic_action_search"
        android:orderInCategory="99"
        app:showAsAction="ifRoom|collapseActionView"
        app:actionViewClass=".views.EventSearchView"
        />
    <item
        android:id="@+id/action_settings"
        android:title="@string/action_settings"
        android:orderInCategory="100"
        app:showAsAction="never" />
</menu>

A: Fully Qualified Package Name and the xmlns:app="http://schemas.android.com/apk/res-auto" namespace did the trick. I must have had a typo somewhere.


text:
Q: NameError: name 'fish' is not defined I'm a newbie in Python and trying to figure out the problem i'm facing.  I'm getting following error msg:
     16     return output
     17
---> 18 print(fishstore(fish, price))
     19
     20

NameError: name 'fish' is not defined

Script i'm working on:
def fishname():
    user_input=input("Enter Name: ")
    return (user_input.title())

def number():
    number_input=input("Enter Price: ")
    return number_input

def fishstore(fish, price):
    fish_entry = fishname()
    price_entry = number()
    output = "Fish Type: " + fish_entry + ", costs $" + price_entry
    return output

print(fishstore(fish, price))

Could someone explain what i'm missing?
Thank you in advance.
Thank you all for help.  so i did some work and made change...
def fishstore(fish, price):
    output = "Fish Type: " + fish + ", costs $" + price
    return output

fish_entry = input("Enter Name: ")
fish = fish_entry
price_entry = input("Enter Price: ")
price = price_entry

print(fishstore(fish, price))

and it worked.  Thank you all for help!

A: When you're defining the method you're naming arguments:
def fishstore(fish, price):

When you're calling the method you're referencing two variables that don't exist:
fishstore(fish, price)

You probably mean:
fishstore(fishname(), number())

The result of fishname() ends up being fish within the context of that fishstore method, likewise with number() becoming price. Outside of that specific context those variables don't exist.

A: You are getting this error because variable names fish and price are not defined in your program.
print(fishstore(fish, price))

I think you are trying to read the values from user and passing it to fishstore()
This will help you.
version 1
Read inputs directly from fishstore() function.
def fishname():
    user_input=input("Enter Name: ")
    return (user_input.title())

def number():
    number_input=input("Enter Price: ")
    return number_input

def fishstore():
    fish_entry = fishname()
    price_entry = number()
    output = "Fish Type: " + fish_entry + ", costs $" + price_entry
    return output

print(fishstore())

version 2
def fishname():
    user_input=input("Enter Name: ")
    return (user_input.title())

def number():
    number_input=input("Enter Price: ")
    return number_input

def fishstore(fish_entry, price_entry):
    output = "Fish Type: " + fish_entry + ", costs $" + price_entry
    return output

print(fishstore(fishname(), number()))

Both versions will give you the result you are expecting.
output:
Enter Name: tilapia
Enter Price: 10
Fish Type: Tilapia, costs $10


text:
Q: Mysql upgrade 5.7.22 to 8.0, server not starting after upgrade I followed the upgrade guide Upgrading MySQL.
Already installed version of mysql is 5.7.22
Verified all Upgrade Prerequisites for MySQL 5.7 Installation
SET GLOBAL innodb_fast_shutdown = 1;

then after shutdown server using below command :
mysqladmin -u root -p shutdown

Steps followed while upgrading :
cd /tmp/ && wget https://dev.mysql.com/get/mysql-apt-config_0.8.10-1_all.deb
dpkg -i mysql-apt-config_0.8.10-1_all.deb
        (Reading database ... 8438 files and directories currently installed.)
        Preparing to unpack mysql-apt-config_0.8.10-1_all.deb ...
        Unpacking mysql-apt-config (0.8.10-1) over (0.8.10-1) ...
        Setting up mysql-apt-config (0.8.10-1) ...
        debconf: unable to initialize frontend: Dialog
        debconf: (No usable dialog-like program is installed, so the dialog based frontend cannot be used. at /usr/share/perl5/Debconf/FrontEnd/Dialog.pm line 76.)
        debconf: falling back to frontend: Readline
        Configuring mysql-apt-config
        ----------------------------

        MySQL APT Repo features MySQL Server along with a variety of MySQL components. You may select the appropriate product to choose the version
        that you wish to receive.

        Once you are satisfied with the configuration then select last option 'Ok' to save the configuration, then run 'apt-get update' to load
        package list. Advanced users can always change the configurations later, depending on their own needs.

          1. MySQL Server & Cluster (Currently selected: mysql-5.7)  3. MySQL Preview Packages (Currently selected: Disabled)
          2. MySQL Tools & Connectors (Currently selected: Enabled)  4. Ok
        Which MySQL product do you wish to configure? 1

        This configuration program has determined that mysql-5.7 is configured on your system, and has highlighted the most appropriate repository
        package. If you are not sure which version to install, do not change the auto-selected version. Advanced users can always change the version
        as needed later. Note that MySQL Cluster also contains MySQL Server.

          1. mysql-5.7  2. mysql-8.0  3. mysql-cluster-7.5  4. mysql-cluster-7.6  5. None
        Which server version do you wish to receive? 2

        MySQL APT Repo features MySQL Server along with a variety of MySQL components. You may select the appropriate product to choose the version
        that you wish to receive.

        Once you are satisfied with the configuration then select last option 'Ok' to save the configuration, then run 'apt-get update' to load
        package list. Advanced users can always change the configurations later, depending on their own needs.

          1. MySQL Server & Cluster (Currently selected: mysql-8.0)  3. MySQL Preview Packages (Currently selected: Disabled)
          2. MySQL Tools & Connectors (Currently selected: Enabled)  4. Ok
        Which MySQL product do you wish to configure? 4

        OK

apt-get update
apt-get install mysql-server
        Configuring mysql-community-server
        ----------------------------------

        MySQL 8 uses a new authentication based on improved SHA256-based password methods. It is recommended that all new MySQL Server installations
        use this method going forward. This new authentication plugin requires new versions of connectors and clients, with support for this new 8
        authentication (caching_sha2_password). Currently MySQL 8 Connectors and community drivers built with libmysqlclient21 support this new
        method. Clients built with older versions of libmysqlclient may not be able to connect to the new server.

        To retain compatibility with older client software, the default authentication plugin can be set to the legacy value (mysql_native_password)
        This should only be done if required third-party software has not been updated to work with the new authentication method. The change will be
        written to the file /etc/mysql/mysql.conf.d/default-auth-override.cnf

        After installation, the default can be changed by setting the default_authentication_plugin server setting.

          1. Use Strong Password Encryption (RECOMMENDED)  2. Use Legacy Authentication Method (Retain MySQL 5.x Compatibility)
        Select default authentication plugin 2

after successful installation trying to start mysql server using old mysql data dir. But its not starting server :
mysqld_safe --user=mysql --datadir=/var/lib/mysql
        2018-07-12T06:46:26.378138Z mysqld_safe Logging to '/var/log/mysql/error.log'.
        2018-07-12T06:46:26.391934Z mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
        2018-07-12T06:46:26.396613Z mysqld_safe mysqld from pid file /var/run/mysqld/mysqld.pid ended

and there is no new error in mysql error.log :
2018-07-12T06:42:34.126621Z 0 [Note] Shutting down plugin 'INNODB_TRX'
2018-07-12T06:42:34.126624Z 0 [Note] Shutting down plugin 'InnoDB'
2018-07-12T06:42:34.126724Z 0 [Note] InnoDB: FTS optimize thread exiting.
2018-07-12T06:42:34.126835Z 0 [Note] InnoDB: Starting shutdown...
2018-07-12T06:42:34.227213Z 0 [Note] InnoDB: Dumping buffer pool(s) to /var/lib/mysql/ib_buffer_pool
2018-07-12T06:42:34.227742Z 0 [Note] InnoDB: Buffer pool(s) dump completed at 180712  6:42:34
2018-07-12T06:42:35.902099Z 0 [Note] InnoDB: Shutdown completed; log sequence number 2589862
2018-07-12T06:42:35.903598Z 0 [Note] InnoDB: Removed temporary tablespace data file: "ibtmp1"
2018-07-12T06:42:35.903608Z 0 [Note] Shutting down plugin 'MyISAM'
2018-07-12T06:42:35.903616Z 0 [Note] Shutting down plugin 'sha256_password'
2018-07-12T06:42:35.903618Z 0 [Note] Shutting down plugin 'mysql_native_password'
2018-07-12T06:42:35.903719Z 0 [Note] Shutting down plugin 'binlog'
2018-07-12T06:42:35.903965Z 0 [Note] /usr/sbin/mysqld: Shutdown complete

2018-07-12T06:42:35.978195Z mysqld_safe mysqld from pid file /var/run/mysqld/mysqld.pid ended

A: I had exactly the same problem. To solve it I uninstalled mysql 5.7, made a backup of the / var / lib / mysql directory, then deleted the mysql directory and reinstalled version 8.0. That's the only way I could make it work. This problem occurs because mysql8.0 can not interpret the files generated in version 5.7 of mysql. especially the log files (ib_logfile0 ib_logfile0).
Here is the sequence of commands I used to solve my problem:

sudo yum remove mysql -y
cd ..
cp -av / var / lib / mysql /var/lib/mysql.old
rm -rf mysql
sudo yum install mysql-community-server -y
service mysqld start

And everything worked correctly.
NOTE: Since it was a new installation, I had no old databases. So just perform these procedures and work normally.
Hope this helps.


text:
Q: How to place UI widgets on top of multiple Z ordered Surface Views in Android I have 2 SurfaceViews and 1 button and they need to be arranged in a way similar to the attached screenshot. I was able to get SurfaceView B to be on top of SurfaceView A by calling surfaceViewB.setZOrderOnTop(true);
The problem is that, once I do that, SurfaceView B is placed above the actual Window and I'm no longer able to get the Button to be on top of it (eg. calling button.bringToFront() is useless here).
Any idea how this layout could be accomplished?

A: You can use setZOrderMediaOverlay(boolean) to place SurfaceView B over SurfaceView A, but still behind the window. From documentation: Link:

public void setZOrderMediaOverlay (boolean isMediaOverlay)
Control whether the surface view's surface is placed on top of another
  regular surface view in the window (but still behind the window
  itself). This is typically used to place overlays on top of an
  underlying media surface view.
Note that this must be set before the surface view's containing window
  is attached to the window manager.
Calling this overrides any previous call to setZOrderOnTop(boolean).

So, the following should work for you:
surfaceViewB.setZOrderMediaOverlay(true);


text:
Q: Не удается запустить mysql на Linux (Fedora) После выполнения команды:
yum -y install mysql mysql-server

зависимости все разрешены и установка была выполнена.
Далее запускаю mysql:
service mysql start

результат получаю такой:
Redirecting to /bin/systemctl start mysql.service
Failed to start mysql.service: Unit mysql.service not found.

Будьте добры, объясните.

A: Использовал другую команду для запуска:
sudo service mariadb start


text:
Q: How to properly save an item in CoreData with SwiftUI MVVM? I am working on implementing CoreData/Cloudkit in my project. It is built in SwiftUI using the MVVM architecture. I am stuck on the part where I am saving/adding something to CoreData, in the Xcode template provided by Apple, this is done in the ContentView file, however to me this feels like something that should be done in the ViewModel. Is that correct?
For additional context, my project is a simple game and the score is calculated in the viewModel. The score is then immediately displayed to the user through the ContentView. I also want to be able to save the score to a Leaderboard CoreData object. Since most of the work done with the score is done in the viewModel, it makes most sense to me for the saving to be handled there instead of in the view.
The template does the saving through the following code
let newItem = Item(context: viewContext)
            newItem.timestamp = Date()

            do {
                try viewContext.save()

where viewContext is @Environment(\.managedObjectContext) private var viewContext
How would I go about doing this in the ViewModel since I believe @Enviroment is for SwiftUI.

A: I followed a tutorial by SwiftfullThinking and I think his explanation and implementation is great.
So ViewModel is also the PersistenceController:
class ViewModel: ObservableObject {

let container: NSPersistentContainer

@Published var savedData: [Entity] = []

init() {
    container = NSPersistentContainer(name: "DataContainer") //exactname of the CoreData file
    container.loadPersistentStores { (description, error) in
        if let error = error {
            fatalError("Error: \(error.localizedDescription)")
        }
    }
}

func getData() {
    let request = NSFetchRequest<TargetEntity>(entityName: "Entity") //exact name as in the CoreData file

    do {
        try savedData = container.viewContext.fetch(request)
    } catch {
        print("Error getting data. \(error.localizedDescription)")
    }

}

func addData(dataToSave: String) {
    let newEntity = Entity(context: container.viewContext)
    newEntity.data = dataToSave
    saveData()
}

func saveData() {
    do {
        try container.viewContext.save()
        getData() //to update the published variable to reflect this change
    } catch let error {
        print("Error: \(error)")
    }
}

}
Let me know if you have questions about this.


text:
Q: DataBinding to Charts I am trying to create some charts for a C# .NET 4.0 Winforms application. I have begun with the pie-Chart. Is there a way to use databinding in order to keep the chart updated?
So far I have only managed to use the DataPoint.YValues property to change the chart's appearance.
The Series object has got a DataSource property, but I am not sure how to use this DataSource for the single points (which are inside a list, inside the series property).
I hope I could explain my question detailed enough.
PS: The charts are from the System.Forms.DataVisualization.Charting namespace.


text:
Q: Access to parent's private properties through nested types in C# Nested types in C# have the ability to access the parent's private properties. Is there a specific reason for having this language feature ? In my opinion this breaks encapsulation. If I make the nested type public, then I would be able to expose private properties of parent class through it.

A: You would be able to - but you can only nest the class if you've got it in the same source file as the outer class in the first place.
Effectively the nested class is "owned" by the outer class, and trusted to the same extent as any other member of the outer class. A method in the outer class could expose a private property too - but you trust it not to, because you own all that code. Likewise you (the author of the outer class) own all the code of a nested class. If you don't want to break encapsulation in the nested class, just avoid writing code that would break encapsulation :)

A: A nested class is a part of the enclosing class, just like a method is. Exposing private properties through them does not break encapsulation any more than exposing private properties through methods does.
The model that C# uses for access control is that you can access anything you want within the class you're defining, and it's hard to see how it could work any other way.

A: (IMO) The nested type is a part of the enclosing type, and so it should have access to the private members - just like any other part of that type.
Just like if you make any other part of a type public, that too could expose private properties of the type.
Since only the person who wrote the enclosing type could write the nested type, there's no real risk?


text:
Q: Sets of arrays of different length (Python) E.g., when processing the set of plane contours:
each one consists of N nodes and may be described by the matrix N*2
(x, y coordinates of every node).
In MATLAB it may be done with cell array Contours{}.
Every element corresponds to one contour and storeы the array of coordinates of the nodes.
What is the recommended object (data type) in Python for such set of contours ?


text:
Q: Integrate year in nested logit R I want to make a nested logistic regression in R with the package mlogit
I test how producer's decision to enter organisations (14 organisations) or not is affected by different factors....
But I have question: How can I integrate the year variable in my regression (2005-2010)
because for example producer can be in specific organisation in 2005 but an other in 2006...
other question :Can I draw the tree decision in R?
Your help is very much appreciated. Many thanks.

A: If you want use regression, you need to use each year as a separate variable and set to 1 for actual year and to 0 for all others (thus making them separate binary attributes). E.g. you will have attributes:
att1, att2, att3, year2005, year2006, ..., year2012, ...

If you are going to use decision trees, you can represent years as categorical attribute (factors in R).
And yes, it is possible to plot decision trees in R. Take a look at rpart package (usage examples)


text:
Q: when $\lim_{n\to\infty }\sum_{k=0}^n\binom{n}{k}x^k$ exist? When does $$\lim_{n\to\infty }\sum_{k=0}^n\binom{n}{k}x^k\ \ ?$$
My first way : Since $$\sum_{k=0}^n\binom{n}{k}x^k=(1+x)^n$$
the limit exist when $x\in ]-2,0]$ et it's limits is $0$ when $x\in ]-2,0[$ and $1$ if $x=0$.
My second way : Using D'Alembert, I have that $$\lim_{k\to \infty }\left|\frac{\binom{n}{k+1}}{\binom{n}{k}}\right|=\lim_{k\to\infty }\left|\frac{n-k}{k+1}\right|=1$$
and thus it converge if $|x|<1$. Therefore I find the convergence for $x\in ]-1,1[$ what contradict my first answer.
What is the problem ?

A: Notice that the series is defined as
$$\sum_{n=0}^{\infty}{a_n} = \lim_{n \to \infty} \sum_{k=0}^{n}{a_k}.$$
Your example does not fit into the definition, because you would have
$$a_k = \binom{n}{k}x^k$$
and your $a_k$ would depend on $n$, but $n$ is different for different partial sums. So this is not description of infinite series and you cannot use D'Alembert ratio test. Your second approach is not valid.


text:
Q: Semi-directed first-passage percolation on $\mathbb{Z}^2$ with deterministic vertical weights Consider the following first-passage percolation problem on the plane grid $\mathbb{Z}^2$: all the horizontal edges are directed (pointing east) and carry an independent random weight, say standard exponential. All the vertical edges are undirected and carry a deterministic weight, say $c$.
As usual, the length of a path between two vertices is the sum of the weights of its edges. I am interested in the geometry of the shortest path between the origin and the point $(n,0)$. I am particular interested in the limit $n\to\infty$ when $c=c_n$ is allowed to vary (get smaller) with $n$
Question: Has this model been studied before? What are recommended references to start reading about it?
Below is a picture for $n=100$ and $c=0.05$;

Edit:
The specification that the horizontal edges are directed is superfluous. Having undirected horizontal edges results in the same model.


text:
Q: database design: problem with updating a table i have a problem with designing db tables. for explaining my problem here is a simple forum db.
the forum table contains following columns:
|  forum_id  |    title      |     desc     |   last_update    |
------------------------------------------------------------
|      1     |    'title'    |    'desc'    |    2011/5/3      |

now when i design this table should i allow null values for the title, desc and last_update columns or not??
if i think logically, a forum should always have value for title and desc columns while the last_update column could be null or not null but if the user tries to update the title column, he/she has to provide the desc value also. so this is not good since with this approach we have to find the desc value of the forum that we're editing and pass it again to the sql statement which will result to an unecessary overwrite of value that already exist!
problem 1: at the other hand, if i declare seperate sps for each of update statements(one for each column update)  and my table is big enough then that would cause the db to become full of sps that basically do the same thing on the same table.
problem 2: if i allow null values then an update like this will compromise my data integrity:
update ForumDB(title, desc, last_update)
values ('edited title', null, 2011/6/4)
where forum_id = 1

so what can be done to prevent both of this side effects??

A: I agree with Nivas it doesn't sound like these columns should be nullable as you should just enforce the rule that a forum cannot be created without these 2 mandatory values.
Regardless anyway from your problem 2 it sounds like you definitely want to disallow updates to null in any case.
So you could have a generic UPDATE procedure that accepts all parameters and interprets a NULL parameter as meaning leave the original value alone.
SET title = COALESCE(@title, title),
    Desc= COALESCE(@Desc,Desc)

You would need to check if there are any performance implications of these non updating updates in your RDBMS. For SQL Server some information on this can be found here.

A: A database is designed to hold data, the is the only purpose of the database (and is by no means a small task). And data is one of the most (if not the most) important parts of your application.
So you do something (anything) that will not compromise the integrity of your data.
How you access, how you update are relatively less important than data integrity. They can always be optimized. You cannot compromise on data integrity.
(If you want some pointers on how to optimize, you have to specify the technology you are using and the approach you are following/planning to follow)
So: You do not allow null values for the title and the desc columns.
Problem 2 is actually not a problem at all: The size of the stored procedure (If that is what you meant by SP) to update the database is not dependent on the volume of the data. Even if you have a huge table, you still have only one (or a bunch) of stored procedures to manipulate the data.
Problem 2 can be solved by multiple approaches, depending on the technology you are using. Even if you have a hundred columns, your application will not have hundred different actions, each for a column. Columns are logically grouped, you update a set of them per update. You will definitely not need a separate procedure for each column.
Your application architecture and design matters here. Let us take a simple scenario: A UI where you allow the user to view the name and description of a forum and to update them both.
You are worried that the user may want to update only the title and for this you have to fetch the latest description and update them both.
But why?
You will have to fetch them both anyway. To display them. You can use the same values to update. All you have to make sure is that someone else has not already updated the column and you are overwriting them. You can use the modified_by column to check whether the data you have is the latest or not. (One of the reasons why this column should hold the time in addition to the date).
See Should you enforce constraints at the database level as well as the application level? for a discussion on a similar topic.


text:
Q: Why do recipes promote overriding getItemViewType and getViewTypeCount when it doesn't seem necessary? I've been working through the Commonsware Android Programming Tutorials and in tutorial 5, extra credit 2, the challenge is to use multiple layouts for displaying rows in a ListView depending on the "type name" of the object (a Restaurant's "type" attribute, which is a String). As such, it suggests overriding getItemViewType and getViewTypeCount in a custom ArrayAdapter. In addition, the android docs and other online recipes or blog posts suggest the same.
In this situation, following this recipe and overriding those two methods works fine but results in redundant logic based on inspecting the value of that Restaurant "type" attribute. For example (note that this adapter is an inner class and restaurants is an ArrayList of Restaurant objects declared as a member of the outer Activity):
class RestaurantsAdapter extends ArrayAdapter<Restaurant> {

  private static final int ROW_TYPE_DELIVERY = 0;
  private static final int ROW_TYPE_TAKE_OUT = 1;
  private static final int ROW_TYPE_SIT_DOWN = 2;

  RestaurantsAdapter() {
    super(LunchListActivity.this, android.R.layout.simple_list_item_1, restaurants);
  }

  public int getViewTypeCount() {
    return 3;
  }

  public int getItemViewType(int position) {
    String type = restaurants.get(position).getType();
    if (type == "delivery") {
      return ROW_TYPE_DELIVERY;
    } else if (type == "take_out") {
      return ROW_TYPE_TAKE_OUT;
    } else {
      return ROW_TYPE_SIT_DOWN;
    }
  }

  // Sets the icon, name and address of the Restaurant for the view.
  public View getView(int position, View convertView, ViewGroup parent) {
    View row = convertView;
    RestaurantHolder viewHolder;

    if (row == null) {
      LayoutInflater inflater = getLayoutInflater();
      switch (getItemViewType(position)) {
        case ROW_TYPE_DELIVERY:
          row = inflater.inflate(R.layout.row_delivery, null);
          break;
        case ROW_TYPE_TAKE_OUT:
          row = inflater.inflate(R.layout.row_take_out, null);
          break;
        default:
          row = inflater.inflate(R.layout.row_sit_down, null);
          break;
      }

      viewHolder = new RestaurantHolder(row);
      row.setTag(viewHolder);
    } else {
      viewHolder = (RestaurantHolder)row.getTag();
    }

    viewHolder.populateFrom(restaurants.get(position));

    return row;
  }

}

What bugs me is the duplicate logic (the if/else in getItemViewType and the switch in getView). So, I changed my implementation to the following:
class RestaurantsAdapter extends ArrayAdapter<Restaurant> {

  RestaurantsAdapter() {
    super(LunchListActivity.this, android.R.layout.simple_list_item_1, restaurants);
  }

  // Sets the icon, name and address of the Restaurant for the view.
  public View getView(int position, View convertView, ViewGroup parent) {
    View row = convertView;
    RestaurantHolder viewHolder;

    if (row == null) {
      LayoutInflater inflater = getLayoutInflater();
      if (restaurants.get(position).getType() == "delivery") {
        row = inflater.inflate(R.layout.row_delivery, null);
      } else if (restaurants.get(position).getType() == "take_out") {
        row = inflater.inflate(R.layout.row_take_out, null);
      } else {
        row = inflater.inflate(R.layout.row_sit_down, null);
      }
      viewHolder = new RestaurantHolder(row);
      row.setTag(viewHolder);
    } else {
      viewHolder = (RestaurantHolder)row.getTag();
    }

    viewHolder.populateFrom(restaurants.get(position));

    return row;
  }

}

This accomplishes the goal of dynamically loading one of three xml layouts, removes the redundant logic, slightly reduces coupling of code to the number of layouts, and does not require overriding getViewTypeCount and getItemViewType.
My question is: why should one override those two methods if one does not have to?

A:
why should one override those two methods if one does not have to?

Add a few dozen restaurants, all of differing types, and watch as your row recycling goes haywire when you scroll, given your implementation shown above.
getItemViewType() and getViewTypeCount() are to ensure that row recycling works. Android will maintain separate object pools and will only hand you a row back to recycle that is of the correct type.
In your solution, you could inflate a R.layout.row_delivery row, then later get it handed back to you for recycling when you are really in need of a R.layout.row_sit_down row.
BTW, do not use inflate(R.layout.row_take_out, null) in an AdapterView. To get RelativeLayout rules to process correctly, use inflate(R.layout.row_take_out, parent, false).


text:
Q: Getting segmentation fault when sorting an linked list So here is the my sorting function, i'm not swapping the info from the linked list just the pointers for the next node. I have a similar function that sorts by the price of the car that works perfectly, when i use to sort by the year of the car i get segmentation fault 11.
void ordenaCrescenteAno(ELEMCAR *iniLista){
  ELEMCAR *aux1 = NULL;
  ELEMCAR *aux2 = NULL;
  ELEMCAR *maior = NULL;
  ELEMCAR *troca = NULL;

  if(iniLista == NULL){
    printf("Lista Vazia\n");
    return;
  }

  for(aux1 = iniLista; aux1 != NULL; aux1 = aux1 -> seguinte){
    maior = aux1;
    for(aux2 = aux1; aux2 != NULL; aux2 = aux2 -> seguinte){
       if(aux2->info.ano > maior->info.ano){
          maior = aux2;
       }
    }
    if(maior != aux1){
      troca->seguinte = aux1->seguinte;
      aux1->seguinte = maior->seguinte;
      maior->seguinte = troca->seguinte;
    }

 }
}

I'm gonna put here the details of the linked list:
typedef struct carro{
    char matricula[7];
    char marca[30];
    char modelo[30];
    int ano;
    char classe[30];
    float preco;
    char combustivel[10];
    int dataInspecao;
    int dataRevisao;
    char observacoes[100];
    int estado;
}CARINFO;

typedef struct CarElem{
    CARINFO info;
    struct CarElem *seguinte;
}ELEMCAR;

What am i doing wrong? I can't figure it out, since i have a similar function that works, but i'm sorting by the "preco" variable.

A: troca is initialized to null so troca->sequinte will fault
Use this instead
struct CarElem *troca; replace troca definition

troca = aux1->sequinte; replace troca->sequinte line with this
maior->sequinte = troca; remove ->sequinte from troca

I realized that the above code snippet was buggy.
In your swapping part
if (maior != aux1)
{
  CARINFO carswap = aux1->info; // Copy the info into a temporary variable
  aux1->info = maior->info;     // Move info from maior to aux1
  maior->info = carswap;        // Move info from temporary variable to maior
}

Hope this code snippet does what you require